package http_proxy_middleware

import (
	"regexp"
	"strings"

	"github.com/gin-gonic/gin"
)

// ^/test_http_service/abbb(.*) /test_http_service/baaa$1  // 将匹配到的“/test_http_service/abbb” 放入转为“/test_http_service/baaa”位置
// HTTPUrlRewriteMiddleware url重写 匹配路径
func HTTPUrlRewriteMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceDetail := GetServiceDetail(c)
		for _, v := range strings.Split(serviceDetail.HTTPRule.UrlRewrite, ",") {
			items := strings.Split(v, " ")
			if len(items) != 2 {
				continue
			}
			reg, err := regexp.Compile(items[0])
			if err != nil {
				//log.Println("regexp.Compile err",err)
				continue
			}
			//log.Println("before rewrite",c.Request.URL.Path)
			c.Request.URL.Path = string(reg.ReplaceAll([]byte(c.Request.URL.Path), []byte(items[1])))
			//log.Println("after rewrite",c.Request.URL.Path)
		}
		c.Next()
	}
}
